import {decode, encode} from './ecode'

export const sessionStorage = {
  setItem: (...args) => setItem(window.sessionStorage, ...args),
  getItem: (...args) => getItem(window.sessionStorage, ...args),
  removeItem: (...args) => removeItem(window.sessionStorage, ...args)
}

export const localStorage = {
  setItem: (...args) => setItem(window.localStorage, ...args),
  getItem: (...args) => getItem(window.localStorage, ...args),
  removeItem: (...args) => removeItem(window.localStorage, ...args)
}

function getItem(storage, name, needParse) {
  name = String(name)
  if(!name) return
  let result = storage.getItem(encode(name))
  if (result) {
    result = decode(result)
  }
  let reg = /^(\[|\{)[\s\S]*(\]|\})$/g
  if (needParse && reg.test(result)) {
    return JSON.parse(result)
  }
  return result
}
/**
 * @func 本地存储存数据
 * @return <Object, String>
 * @param name <Object, String> 存储名称
 * @param value <String> 存储值
 */
function setItem(storage, name, value) {
  name = String(name)
  if (!name) return
  if (value.constructor === Object || value.constructor === Array) {
    value = JSON.stringify(value)
  }else {
    value = String(value)
  }
  storage.setItem(encode(name), encode(value))
}
/**
 * 清除本地缓存
 */
function removeItem(storage, name) {
  name = String(name)
  if(!name) return
  storage.removeItem(encode(name))
}